<template>
  <div class="big-box">

    <!-- 选项卡列 -->
    <div class="box-left">

      <!-- 在box-left里面包一层让他粘顶 -->
      <div style="position: sticky; top: 60px">
        <!-- 页面的全部数据 -->
        <!-- {{ ExamInfo }} -->
        <!-- 左边第一个 -->
        <div class="reminder-info">
          <!-- 【还不知道写什么在这里】注意事项：比如多就就自动保存一次
          还有一个返回上一级的按钮 退出键 -->
        </div>

        <div class="test-time">
          <!--ExamInfo.timeRemaining != undefined 获取到了剩余时间，才开始计算考试  -->
          倒计时： <count-down v-if="ExamInfo.timeRemaining != undefined" :time="ExamInfo.timeRemaining"
            @sendTimeOut="timeOut()"></count-down>
        </div>
        <span class="xh">序号 :</span>
        <!-- 左边第三个答题卡 -->
        <div class="answer-sheet">
         
          <button @click="handleLeft(index)" class="number-button" v-for="(item, index) in ExamInfo.reply" :key="index"
            :class="{ answered: item.reply != '' }">
            {{ index + 1 }}
          </button>
        </div>

        <!-- 左边第四个 -->
        <div class="submit-box">
          <button @click="showModal=true" class="submit-button">提交</button>
          <!-- <button @click="onExit()" class="submit-button">退出</button> -->
        </div>
      </div>

    </div>

    <!-- 试卷题目栏  选项框禁止选中disabled-->
    <div class="box-right">
      <!-- 整张试卷题目等 -->
      <div class="exam-main-title">
        <span style="font-family: '华文新魏'; font-size: 36px">{{ ExamInfo.title }}</span>
        <span style="font-family: '华文楷体'; margin: 10px 0px 10px 0px;font-size: 16px;">
          题目数量:{{ topicNumber }}&nbsp;&nbsp;满分:{{ ExamInfo.fullMark }}&nbsp;&nbsp;限时:{{ timeLimitText }}
        </span>
      </div>

      <!-- 试题 -->
      <div @click="getChenge" v-for="(topicItem, index) in ExamInfo.topics" :key="index"
        :class="{ 'skip-style': index === navgatorIndex }" class="exam-details" :id="'id' + index">

        <!-- 试题 -->
        <div class="shi-ti-style">
          <!-- 题目 -->
          <span>{{ index + 1 }}、{{ topicItem.title }}【分值:{{ topicItem.score }}】</span>
          <!-- 选项 -->

          <div class="xuan-xiang-style">

            <!-- 单选 -->
            <!-- 找到对应的答题卡答题位置 但是可能有问题 可以用 @input="onLog(topicItem, index)"解决 无法根据题目id找到答题位置 v-model="ExamInfo.reply[index].reply" -->
            <el-radio-group v-if="topicItem.type == '单选'" v-model="ExamInfo.reply[index].reply"
              @input="onLog(topicItem, index)" style="display: flex;flex-direction: column;align-items: flex-start">
              <el-radio v-for="optionItem in topicItem.options" :value="optionItem.option" :key="optionItem.option">
                {{ optionItem.option }} {{ optionItem.text }}
              </el-radio>
            </el-radio-group>


            <!-- 多选 -->
            <el-checkbox-group v-else-if="topicItem.type == '多选'" v-model="ExamInfo.reply[index].reply"
              @change="onLog(topicItem, index)" style="display: flex;flex-direction: column;align-items: flex-start">
              <el-checkbox v-for="optionItem in topicItem.options" :value="optionItem.option" :key="optionItem.option">
                {{ optionItem.option }} {{ optionItem.text }}
              </el-checkbox>
            </el-checkbox-group>


            <!-- 判断题-->
            <el-radio-group v-else-if="topicItem.type == '判断'" v-model="ExamInfo.reply[index].reply"
              @input="onLog(topicItem, index)">
              <el-radio v-for="optionItem in topicItem.options" :value="optionItem.option" :key="optionItem.option">
                {{ optionItem.option }}
              </el-radio>
            </el-radio-group>

            <!-- 简答 -->
            <div v-else-if="topicItem.type == '简答'">
              <el-input @blur="onLog(topicItem, index)" type="textarea" :rows="4" placeholder="-在此作答-"
                v-model="ExamInfo.reply[index].reply" />
            </div>
            <!-- 编程题 -->
            <div v-else-if="topicItem.type == '编程'" style="margin-top: 20px;">
              <code-editor @click="onLog(topicItem, index)" v-model="ExamInfo.reply[index].reply"></code-editor>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

<!-- 确认提交试卷 -->
<n-modal v-model:show="showModal"  :mask-closable="false">
        <n-card style="width: 400px;height: 300px;" title=" " role="dialog" aria-modal="true">
            <!-- 关闭框 -->
            <template #header-extra>
                <img src="/src/assets/svg/delete.svg" class="deleye-img" @click="showModal = false">
            </template>
            <div style="display: flex;flex-direction: column;">
                <span style="text-align: center;font-size: 20px;margin-bottom: 10px;">确认交卷</span>
                <span>1. 交卷前,请仔细检查试卷无误。</span>
                <span>2. 交卷后,将无法再次进入本场考试。 </span>
            </div>
            <!-- 提交按钮 -->
            <template #footer>
                <div style="display: flex;justify-content: flex-end;">
                    <n-button @click="getSubmit()">确认交卷</n-button>
                </div>
            </template>
        </n-card>
    </n-modal>

</template>

<script setup>
import studentHttp from "@/api/studentHttp";
import CodeEditor from "@/components/utils/CodeEditor.vue";
import CountDown from "@/components/utils/CountDown.vue";
import { openInfo } from "@/utils/openInfo";
import timeUtils from "@/utils/timeUtils";
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onBeforeMount, onBeforeUnmount, onMounted, onUnmounted, ref } from "vue";
import { useRouter } from "vue-router";
const router = useRouter()
const showModal = ref(false)
//页面数据
const ExamInfo = ref({})
//页面基础数据
const topicNumber = computed(() => {
  //如果拿到了数据就渲染题目数量上去
  if (ExamInfo.value.reply != undefined) {
    return ExamInfo.value.reply.length
  }
  return '获取题目数量失败'
})
const timeLimitText = computed(() => {
  return timeUtils.HMS(ExamInfo.value.timeLimit)
})

//到时间了自动触发交卷 或者到截至时间了自动触发交卷
function timeOut() {
  //  考虑页面刷新对考试的影响------时间保存到本地
  getSubmit()
}

// 每写一题就交一次试卷填
function onLog(topicObj, index) {
  const from = {
    answerSheetId: ExamInfo.value.answerSheetId,//答卷Id
    reply: ExamInfo.value.reply,//答题卡
    timeRemaining: ExamInfo.value.timeRemaining,
    //examStore: "进行中",
  }
  studentHttp.midwaySubmit(from).then((res) => {
    console.log(res);
  })
}

//通过路由传参获取这次考试的答卷Id
const props = defineProps(['answerSheetId'])
const answerSheetId = props.answerSheetId

//获取考试信息
async function getExamInfo() {
  studentHttp.starTest(answerSheetId).then((res) => {
    ExamInfo.value = res.data;
    console.log("完整数据", res.data);
    startCountdown()
  })
}

//序号选中的index------------------------------------------------
const navgatorIndex = ref(null);
//点击跳转到指定位置
function handleLeft(index) {
  //选中
  navgatorIndex.value = index;
  // 根据id获取dom元素
  const element = document.querySelector(`#id${index}`);
  element.scrollIntoView({
    top: "100px",
    behavior: "smooth", // 平滑过渡
    block: "center", // 上边框与视窗顶部平齐。默认值
  });
}

//考试计时---------------------------------------------------------------

//定时器
let timer = null
function startCountdown() {
  timer = setInterval(() => {
    if (ExamInfo.value.timeRemaining > 0) {
      ExamInfo.value.timeRemaining -= 1000; // 每秒减少 1000 毫秒
      //每一秒提交一次试卷
      //onLog()
    } else {
      // 倒计时结束交卷 有两倒计时，应该删除一个
      getSubmit()
      clearInterval(timer);
    }
  }, 1000);
};






const handleBeforeUnload = (event) => {
  onLog()
  // 设置返回值以触发浏览器的默认确认框
  event.returnValue = '数据已保存！考试还未结束，还未交卷，您确定要现在离开当前页面吗？';
  return '数据已保存！考试还未结束，还未交卷，您确定要现在离开当前页面吗？';
};

onMounted(() => {
  //获取初始化的数据
  getExamInfo()
  window.onbeforeunload = handleBeforeUnload;
})

// 清除事件处理器
onUnmounted(() => {
  window.onbeforeunload = null;
});



//提交试卷-------------------------------------------
function getSubmit() {
  const from = {
    answerSheetId: ExamInfo.value.answerSheetId,//答卷Id
    reply: ExamInfo.value.reply,//答题卡
    //timeRemaining: ExamInfo.value.timeRemaining,
    //examStore: "进行中",
  }
  studentHttp.submitExam(from).then((res) => {
    console.log(res);
    window.onbeforeunload = null;
    openInfo("试卷提交成功!")
    router.push({name:'StudentExam'})
  })
}
//退出考试
function onExit() {
  openInfo("退出成功！", "success");
}


</script>

<style scoped>
/* 最大的盒子 */
.big-box {
  border: 1px rgb(72, 34, 34, 0.2) solid;
  display: flex;
  flex-direction: row;
}

/* 左侧---------------------------------------- */

.box-left {
  padding: 5px;
  width: 30%;
  position: sticky;
  top: 0px;
  /* 元素将粘在页面顶部 */
  min-width: 300px;
  border-right: 2px rgb(67, 51, 51, 0.2) dashed;
  border-radius: 10px;
}

/* .答题卡 */
.answer-sheet {
  display: flex;
  flex-wrap: wrap;
  border-radius: 10px;
  border: 1px rgb(190, 190, 190, 0.5) solid;
  margin: 10px;
  padding: 5px;
  transition: box-shadow 0.5s ease;
}

.answer-sheet:hover {
  box-shadow: 0px 7px 30px 0px rgba(100, 100, 111, 0.2);
}

/* 序号二字 */
.xh {
  margin-left: 10px;
  user-select: none;
  font-family: "宋体";
}

/* 每一个序号按钮的样式 */
.number-button {
  width: 40px;
  height: 30px;
  margin: 8px;
  color: rgb(0, 0, 0, 0.5);
  font-size: 14px;
  background-color: rgb(255, 255, 255);
  cursor: pointer;
  user-select: none;
  border: 1px rgb(159, 158, 156, 0.5) solid;
  border-radius: 5px;
  transition: background-color 0.3s ease-in-out;
}

.number-button:hover {
  background-color: rgb(201, 232, 218, 0.5);
}

/* 已经回答 */
.answered {
  color: #fff;
  background: rgb(1, 150, 167);
}

/* 提交按钮 */
.submit-button {
  color: rgb(11, 11, 11, 0.8);
  margin: 10px;
  width: 80px;
  height: 30px;
  user-select: none;
  font-family: "幼圆";
  cursor: pointer;
  background-color: rgb(199, 236, 233);
  border: none;
  border-radius: 8px;
  transition: background-color 0.3s ease-in-out, color 0.4s ease;
}

.submit-button:hover {
  color: rgb(255, 255, 255, 0.8);
  background-color: rgb(83, 184, 176);
  border: 1px rgba(178, 197, 179, 0.2) solid;
}

/* 倒计时 */
.test-time {
  border: 1px rgb(232, 220, 220, 0.5) solid;
  border-radius: 5px;
  margin: 10px;
  padding: 10px;
  margin-top: 50px;
  transition: box-shadow 0.5s ease;
}

.test-time:hover {
  box-shadow: 0px 7px 30px 0px rgba(100, 100, 111, 0.2);
}

/* 右侧的答题卡-------------------------------------- */
.box-right {
  width: 70%;
  padding: 20px;
}

/**试题------------------------ */
.exam-main-title {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}


/* 每一题 */
.exam-details {
  margin-top: 10px;
  padding: 15px 15px 40px 15px;
  border-radius: 5px;
  min-height: 100px;
  border: 2px dashed rgba(195, 184, 186, 0.1);
  background: #fff;
}

/* 选项样式 */
.xuan-xiang-style {
  margin-top: 10px;
}

/* 点击跳转处改变边框 */
.skip-style {
  border: 2px dashed rgba(214, 23, 58, 0.4);
}

/* 修改单选选项框选中颜色 */
.xuan-xiang-style>>>.el-radio__input.is-checked .el-radio__inner {
  background-color: rgb(146, 233, 243);
  border: 1px rgb(154, 237, 248) solid;

}

.box-right>>>.el-radio-group {}

/* 修改单选选中字体颜色 */
.xuan-xiang-style>>>.el-radio__input.is-checked+.el-radio__label {
  color: rgb(181, 213, 198);
}

/* 修改多项框选中的颜色 */
.xuan-xiang-style>>>.el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: rgb(146, 233, 243);
  border: 1px rgb(154, 237, 248) solid;
}

/* 修改多选框选中字体样式 */
.xuan-xiang-style>>>.el-checkbox__input.is-checked+.el-checkbox__label {
  color: rgb(181, 213, 198);
}

/* 关闭弹窗键 */
.deleye-img {
  transition: transform 0.3s ease;
  cursor: pointer;
}

.deleye-img:hover {
  transform: scale(1.2);
}
</style>